﻿using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.Collections.ObjectModel;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using KeyAuthService.Models;
using KeyAuthService.Services;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using System.IO;
using KeyAuthService.Dialogs;

namespace KeyAuthService
{
    /// <summary>
    /// 用于在列表为空时显示空数据模板的转换器
    /// </summary>
    public class CountToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is int count)
            {
                return count == 0 ? Visibility.Visible : Visibility.Collapsed;
            }
            else if (value is ICollection collection)
            {
                return collection.Count == 0 ? Visibility.Visible : Visibility.Collapsed;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// 布尔值反转为可见性的转换器
    /// </summary>
    public class BooleanToVisibilityInverseConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value is bool boolValue)
            {
                return boolValue ? Visibility.Collapsed : Visibility.Visible;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly IServiceProvider _serviceProvider;
        private readonly ILogger<MainWindow> _logger;
        private readonly WebSocketServer _webSocketServer;
        private readonly KeyStorageService _keyStorageService;
        private readonly KeyAuthCore _keyAuthCore;
        private readonly UIService _uiService;
        private readonly DispatcherTimer _statusUpdateTimer;
        private ObservableCollection<KeyInfo> _keyList = new ObservableCollection<KeyInfo>();
        private ObservableCollection<ConnectionInfo> _connectionList = new ObservableCollection<ConnectionInfo>();

        public MainWindow(IServiceProvider serviceProvider)
        {
            InitializeComponent();
            
            _serviceProvider = serviceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<MainWindow>>();
            _webSocketServer = serviceProvider.GetRequiredService<WebSocketServer>();
            _keyStorageService = serviceProvider.GetRequiredService<KeyStorageService>();
            _keyAuthCore = serviceProvider.GetRequiredService<KeyAuthCore>();
            _uiService = serviceProvider.GetRequiredService<UIService>();

            // 初始化列表视图数据源
            lvKeys.ItemsSource = _keyList;
            lvConnections.ItemsSource = _connectionList;

            // 初始化状态更新定时器
            _statusUpdateTimer = new DispatcherTimer();
            _statusUpdateTimer.Interval = TimeSpan.FromSeconds(2); // 更新频率改为2秒
            _statusUpdateTimer.Tick += StatusUpdateTimer_Tick;
            _statusUpdateTimer.Start();

            // 注册窗口关闭事件
            Closing += MainWindow_Closing;

            // 初始化日志
            LogMessage("KeyAuth 系统服务已启动");
            
            // 自动启动服务
            StartService();
            
            // 加载密钥
            LoadKeys();

            // 更新状态
            UpdateStatus();
        }

        /// <summary>
        /// 窗口关闭事件处理
        /// </summary>
        private void MainWindow_Closing(object? sender, System.ComponentModel.CancelEventArgs e)
        {
            // 停止服务
            if (_webSocketServer.IsRunning)
            {
                _webSocketServer.Stop();
                LogMessage("服务已停止");
            }
        }

        /// <summary>
        /// 状态更新定时器
        /// </summary>
        private void StatusUpdateTimer_Tick(object? sender, EventArgs e)
        {
            UpdateStatus();
            UpdateConnectionList();
        }

        /// <summary>
        /// 更新状态显示
        /// </summary>
        private void UpdateStatus()
        {
            try
            {
                // 更新服务状态
                if (_webSocketServer.IsRunning)
                {
                    statusIndicator.Background = Brushes.Green;
                    statusText.Text = "运行中";
                    btnStartStop.Content = "停止服务";
                    txtStatus.Text = "服务运行正常";
                }
                else
                {
                    statusIndicator.Background = Brushes.Gray;
                    statusText.Text = "未启动";
                    btnStartStop.Content = "启动服务";
                    txtStatus.Text = "服务未运行";
                }

                // 更新密钥数量
                var keys = _keyStorageService.GetAllKeys();
                txtKeyCount.Text = $"密钥数量: {keys.Count}";

                // 更新连接数量（从WebSocketServer获取）
                int connCount = _webSocketServer.ConnectedClients;
                txtConnectedClients.Text = $"已连接客户端: {connCount}";
                txtConnectionCount.Text = connCount.ToString();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新状态显示时发生异常");
            }
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        private void StartService()
        {
            try
            {
                if (!_webSocketServer.IsRunning)
                {
                    if (_webSocketServer.Start())
                    {
                        LogMessage("服务已启动，监听地址: ws://127.0.0.1:9876");
                        UpdateStatus();
                    }
                    else
                    {
                        LogMessage("启动服务失败");
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "自动启动服务时发生异常");
                LogMessage($"启动服务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 加载密钥列表
        /// </summary>
        private void LoadKeys()
        {
            try
            {
                // 清空列表
                _keyList.Clear();
                
                // 获取所有密钥
                var keys = _keyStorageService.GetAllKeys();
                
                // 添加到列表
                foreach (var key in keys)
                {
                    _keyList.Add(key);
                }
                
                LogMessage($"已加载 {keys.Count} 个密钥");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "加载密钥列表时发生异常");
                LogMessage($"加载密钥列表失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新连接列表
        /// </summary>
        private void UpdateConnectionList()
        {
            try
            {
                if (_webSocketServer.IsRunning)
                {
                    // 获取当前连接信息
                    var currentConnections = _webSocketServer.ActiveConnections;

                    // 在UI线程中更新列表
                    Dispatcher.Invoke(() =>
                    {
                        // 清空列表
                        _connectionList.Clear();
                        
                        // 添加连接信息
                        foreach (var conn in currentConnections)
                        {
                            _connectionList.Add(conn);
                        }
                    });
                }
                else
                {
                    // 如果服务未运行，清空列表
                    Dispatcher.Invoke(() => _connectionList.Clear());
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新连接列表时发生异常");
            }
        }

        /// <summary>
        /// 启动/停止服务按钮点击事件
        /// </summary>
        private void btnStartStop_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (_webSocketServer.IsRunning)
                {
                    // 停止服务
                    if (_webSocketServer.Stop())
                    {
                        LogMessage("服务已停止");
                    }
                    else
                    {
                        LogMessage("停止服务失败");
                    }
                }
                else
                {
                    // 启动服务
                    if (_webSocketServer.Start())
                    {
                        LogMessage("服务已启动，监听地址: ws://127.0.0.1:9876");
                    }
                    else
                    {
                        LogMessage("启动服务失败");
                    }
                }

                UpdateStatus();
                UpdateConnectionList();
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动/停止服务时发生异常");
                LogMessage($"操作失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 刷新密钥按钮点击事件
        /// </summary>
        private void btnRefreshKeys_Click(object sender, RoutedEventArgs e)
        {
            LoadKeys();
        }

        /// <summary>
        /// 清除日志按钮点击事件
        /// </summary>
        private void btnClearLog_Click(object sender, RoutedEventArgs e)
        {
            txtLog.Clear();
            LogMessage("日志已清除");
        }

        /// <summary>
        /// 密钥选择变更事件
        /// </summary>
        private void lvKeys_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selectedKey = lvKeys.SelectedItem as KeyInfo;
            
            // 根据是否选中密钥启用或禁用按钮
            btnExportKey.IsEnabled = selectedKey != null;
            btnDeleteKey.IsEnabled = selectedKey != null;
        }

        /// <summary>
        /// 创建密钥按钮点击事件
        /// </summary>
        private void btnCreateKey_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // 输入密钥名称
                string? keyName = _uiService.ShowInputDialog("请输入密钥名称:", "创建新密钥");
                if (string.IsNullOrEmpty(keyName))
                {
                    return;
                }
                
                // 检查名称是否为空
                if (string.IsNullOrEmpty(keyName))
                {
                    _uiService.ShowError("密钥名称不能为空", "输入错误");
                    return;
                }
                
                // 检查是否已存在
                if (_keyStorageService.GetKey(keyName) != null)
                {
                    _uiService.ShowError($"密钥 {keyName} 已存在", "创建失败");
                    return;
                }
                
                // 选择算法
                string[] algorithms = { "SM2", "ECDSA_P256" };
                string? algo = _uiService.ShowSelectionDialog("请选择密钥算法:", "选择算法", algorithms);
                if (string.IsNullOrEmpty(algo))
                {
                    return;
                }
                
                // 确认创建
                bool confirmed = _uiService.ShowConfirmDialog(
                    $"是否创建新的 {algo} 密钥?\n\n名称: {keyName}", 
                    "创建确认");
                    
                if (!confirmed)
                {
                    return;
                }
                
                // 生成密钥
                var (publicKey, privateKey, success) = _keyAuthCore.GenerateKeyPair(algo);
                if (!success)
                {
                    _uiService.ShowError("生成密钥失败", "创建失败");
                    return;
                }
                
                // 创建密钥信息
                var keyInfo = new KeyInfo
                {
                    KeyName = keyName,
                    Algorithm = algo,
                    PublicKey = publicKey,
                    PrivateKey = privateKey,
                    CreatedAt = DateTime.Now
                };
                
                // 保存密钥
                if (_keyStorageService.AddKey(keyInfo))
                {
                    LogMessage($"已创建密钥: {keyName}");
                    LoadKeys(); // 重新加载密钥列表
                    _uiService.ShowSuccess($"密钥 {keyName} 已创建成功", "创建成功");
                }
                else
                {
                    _uiService.ShowError("保存密钥失败", "创建失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建密钥时发生异常");
                LogMessage($"创建密钥失败: {ex.Message}");
                _uiService.ShowError($"创建密钥失败: {ex.Message}", "错误");
            }
        }

        /// <summary>
        /// 导出密钥按钮点击事件
        /// </summary>
        private void btnExportKey_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedKey = lvKeys.SelectedItem as KeyInfo;
                if (selectedKey == null) return;
                
                // 确认导出
                bool confirmed = _uiService.ShowConfirmDialog(
                    $"是否导出密钥 {selectedKey.KeyName}?\n\n此操作会显示敏感信息。",
                    "导出确认", 
                    isWarning: true);
                    
                if (!confirmed) return;
                
                // 创建详细信息窗口
                var keyDetails = $"密钥名称: {selectedKey.KeyName}\n" +
                                $"算法: {selectedKey.Algorithm}\n" +
                                $"创建时间: {selectedKey.CreatedAt}\n\n" +
                                $"公钥:\n{selectedKey.PublicKey}\n\n" +
                                $"私钥:\n{selectedKey.PrivateKey}";
                
                _uiService.ShowTextDetails("密钥详情", keyDetails);
                
                LogMessage($"已导出密钥: {selectedKey.KeyName}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出密钥时发生异常");
                LogMessage($"导出密钥失败: {ex.Message}");
                _uiService.ShowError($"导出密钥失败: {ex.Message}", "错误");
            }
        }

        /// <summary>
        /// 删除密钥按钮点击事件
        /// </summary>
        private void btnDeleteKey_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var selectedKey = lvKeys.SelectedItem as KeyInfo;
                if (selectedKey == null) return;
                
                // 确认删除
                bool confirmed = _uiService.ShowConfirmDialog(
                    $"确定要删除密钥 {selectedKey.KeyName} 吗?\n\n此操作不可恢复。",
                    "删除确认",
                    isWarning: true);
                    
                if (!confirmed) return;
                
                // 删除密钥
                if (_keyStorageService.DeleteKey(selectedKey.KeyName))
                {
                    LogMessage($"已删除密钥: {selectedKey.KeyName}");
                    LoadKeys(); // 重新加载密钥列表
                    _uiService.ShowSuccess($"密钥 {selectedKey.KeyName} 已成功删除", "删除成功");
                }
                else
                {
                    _uiService.ShowError($"删除密钥 {selectedKey.KeyName} 失败", "删除失败");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除密钥时发生异常");
                LogMessage($"删除密钥失败: {ex.Message}");
                _uiService.ShowError($"删除密钥失败: {ex.Message}", "错误");
            }
        }

        /// <summary>
        /// 记录日志
        /// </summary>
        public void LogMessage(string message)
        {
            try
            {
                Dispatcher.Invoke(() =>
                {
                    string timestamp = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
                    txtLog.AppendText($"[{timestamp}] {message}\n");
                    txtLog.ScrollToEnd();
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "记录日志时发生异常");
            }
        }
    }
}